package com.exp.interceptor;

import com.alibaba.fastjson.JSON;
import com.exp.properties.JwtProperties;
import com.exp.result.Result;
import com.exp.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
    public static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    //校验jwt
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        // 设置CORS响应头
//        response.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有域名访问
//        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); // 允许的HTTP方法
//        response.setHeader("Access-Control-Max-Age", "3600"); // 设置 OPTIONS 请求的有效期
//        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization"); // 允许的请求头信息
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getAdminTokenName());

        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            Integer userId = Integer.valueOf(claims.get("userId").toString());
            threadLocal.set(userId);
            //3、通过，放行
            return true;
        } catch (ExpiredJwtException e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.getWriter().write(JSON.toJSONString(Result.error(401, "身份验证过期")));
            return false;
        } catch (Exception e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.getWriter().write(JSON.toJSONString(Result.error(401, "非法访问")));
            return false;
        }
//        catch (Exception ex) {
//            //4、不通过，响应401状态码，拦截
//            response.setStatus(401);
//            return false;
//        }
    }
}
